import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  ListView,
  Image,
  Dimensions,
  ActivityIndicator,
  RefreshControl,
  AlertIOS
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import request from '../common/request'
import { api } from '../common/config'
import Detail from './detail'

const width = Dimensions.get('window').width
let ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2
})

let videos = {
  nextPage: 0,
  data: [],
  total: 0
}

class Item extends Component {
  constructor(props) {
    super(props)

    this.state = {
      up: this.props.row.voted,
      row: this.props.row
    }
  }

  _up() {
    const up = !this.state.up
    const row = this.state.row
    const url = api.base + api.creationsLike

    const body = {
      id: row._id,
      up: up ? 'yes' : 'no',
      accessToken: 'abcd'
    }

    request.post(url, body)
      .then(res => {
        console.log(res)
        if (res && res.success) {
          this.setState({
            up: up
          })
        } else {
          AlertIOS.alert('点赞失败，稍后重试')
        }
      })
      .catch(error => {
        console.warn(error)
        AlertIOS.alert('点赞失败，稍后重试')
      })
  }

  render() {
    const row = this.state.row

    return (
      <TouchableHighlight onPress={this.props.onSelect}>
        <View style={styles.item}>
          <Text style={styles.title}>{row.title}</Text>
          <Image
            source={{ uri: row.thumb }}
            style={styles.thumb}>
            <Icon
              name='ios-play'
              size={28}
              style={styles.play} />
          </Image>
          <View style={styles.itemFooter}>
            <View style={styles.handleBox}>
              <Icon
                name={this.state.up ? 'ios-heart' : 'ios-heart-empty'}
                size={28}
                style={[styles.up, this.state.up ? null : styles.down]}
                onPress={this._up.bind(this)} />
              <Text style={styles.handleText} onPress={this._up.bind(this)}>喜欢</Text>
            </View>
            <View style={styles.handleBox}>
              <Icon
                name='ios-chatboxes'
                size={28}
                style={styles.commentIcon} />
              <Text style={styles.handleText}>评论</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight >
    )
  }
}

class List extends Component {
  constructor(props) {
    super(props)

    this.state = {
      dataSource: ds.cloneWithRows([]),
      isLoadingTail: false,
      isRefreshing: false
    }
  }

  componentDidMount() {
    this._fetchData(1)
  }

  _renderRow(row) {
    return <Item
      key={row._id}
      onSelect={() => this._loadDetailPage(row)}
      row={row} />
  }

  _renderFooter() {
    if (!this._hasMoreData()) {
      return (
        <View style={styles.loadingTip}>
          <Text style={styles.loadingText}>没有更多了</Text>
        </View>
      )
    }

    if (!this.state.isLoadingTail) {
      return <View></View>
    }

    return (
      <ActivityIndicator style={styles.loadingIcon} />
    )
  }

  _fetchData(page) {
    if (page !== 0) {
      this.setState({
        isLoadingTail: true
      })
    } else {
      this.setState({
        isRefreshing: true
      })
    }

    const url = api.base + api.creations

    request.get(url, { page: page })
      .then(res => {
        if (res && res.success) {
          if (res.data && res.data.length > 0) {
            if (page !== 0) {
              ++videos.nextPage
              videos.data = [...videos.data, ...res.data]
              videos.total = res.total

              this.setState({
                dataSource: ds.cloneWithRows(videos.data),
                isLoadingTail: false
              })
            } else {
              videos.nextPage += 1
              videos.data = [...res.data, ...videos.data]
              videos.total = res.total

              this.setState({
                dataSource: ds.cloneWithRows(videos.data),
                isRefreshing: false
              })
            }
          }
        }
      })
      .catch(error => {
        if (page !== 0) {
          this.setState({
            isLoadingTail: false
          })
        } else {
          this.setState({
            isRefreshing: false
          })
        }
        console.warn(error)
      })
  }

  _hasMoreData() {
    return videos.data.length !== videos.total
  }

  _fetchMoreData() {
    if (!this._hasMoreData() || this.state.isLoadingTail) return

    this._fetchData(videos.nextPage)
  }

  _onRefresh() {
    if (!this._hasMoreData() || this.state.isRefreshing) return
    this._fetchData(0)
  }

  _loadDetailPage(row) {
    this.props.navigator.push({
      name: 'detail',
      component: Detail,
      params: {
        video: row
      }
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>列表页面</Text>
        </View>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow.bind(this)}
          renderFooter={this._renderFooter.bind(this)}
          onEndReached={this._fetchMoreData.bind(this)}
          onEndReachedThreshold={20}
          enableEmptySections={true}
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          automaticallyAdjustContentInsets={false}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this._onRefresh.bind(this)}
              tintColor='#ff6600'
              title='玩命加载中...'
              titleColor="#ff6600"
            />
          }
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#000'
  },

  header: {
    paddingTop: 25,
    paddingBottom: 12,
    backgroundColor: '#ee735c'
  },

  headerTitle: {
    color: '#fff',
    fontSize: 16,
    textAlign: 'center',
    fontWeight: '600'
  },

  item: {
    width: width,
    marginBottom: 10,
    backgroundColor: '#fff'
  },

  thumb: {
    width: width,
    height: width * 0.56,
    resizeMode: 'cover'
  },

  title: {
    padding: 10,
    fontSize: 18,
    color: '#333'
  },

  itemFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: '#eee'
  },

  handleBox: {
    padding: 10,
    flexDirection: 'row',
    width: width / 2 - 0.5,
    justifyContent: 'center',
    backgroundColor: '#fff'
  },

  play: {
    position: 'absolute',
    top: 80,
    left: width / 2 - 23,
    width: 46,
    height: 46,
    paddingTop: 9,
    paddingLeft: 18,
    backgroundColor: 'transparent',
    borderColor: '#fff',
    borderWidth: 1,
    borderRadius: 23,
    color: '#ed7b66'
  },

  handleText: {
    paddingLeft: 12,
    fontSize: 18,
    color: '#333'
  },

  up: {
    fontSize: 22,
    color: '#ed7b66',
  },

  down: {
    fontSize: 22,
    color: '#999'
  },

  commentIcon: {
    fontSize: 22,
    color: '#333'
  },

  loadingTip: {

  },

  loadingText: {
    color: '#777',
    textAlign: 'center'
  },

  loadingIcon: {
    marginVertical: 20
  }
})

module.exports = List